<?php

namespace pmvc\mvc\controller;

use pmvc\ioc\ObjectFactory;
use pmvc\ioc\InitializingObject;
use pmvc\mvc\ControllerMapping;
use pmvc\mvc\Controller;
use pmvc\mvc\Request;
use pmvc\util\StringUtil;
use pmvc\util\ClassUtil;
use Exception;

class RegexControllerMapping 
	implements InitializingObject,
	ControllerMapping {
		
	public $regexMap;

	private $objectFactory;

	public function initialize(ObjectFactory $objectFactory) {
		$this->objectFactory = $objectFactory;
	}

	public function getController($url, Request $request) {
		foreach ($this->regexMap as $key => $val) {
			if (StringUtil::matches($key, $url, FALSE)) {

				// get path variables
				$pathVars = StringUtil::extractNamedMatches($url, $key);
				if ($pathVars!=NULL && is_array($pathVars)) {
					foreach ($pathVars as $pVar => $pVal) {
						$request->setPathVariable($pVar, $pVal);
					}
				}

				// get the controller
				$obj = (is_string($val))
					? $this->objectFactory->getObjectById($val)
					: $val;
				if (!ClassUtil::isInstance($obj, 'pmvc\mvc\Controller')) {
					Log::error("Object with mapping {} is not a Controller", $key);
					throw new Exception("Object is not an instance of Controller");
				}
				return $obj;
			}
		}
	}
}


?>